﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Core
{
    /// <summary>
    /// Function
    /// </summary>
    public class Function
    {
        /// <summary>
        /// Function name
        /// </summary>
        private String _Name;
        public String Name
        {
            get { return _Name; }
        }

        /// <summary>
        /// Function arguments
        /// </summary>
        private List<Argument> _Arguments = new List<Argument>();
        public List<Argument> Arguments
        {
            get { return _Arguments; }
        }

        /// <summary>
        /// Function result
        /// </summary>
        private Result _Result;
        public Result Result
        {
            get { return _Result; }
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="input"></param>
        public Function(String input)
        {
            // sample: Max2So (a:R,b:R) kq:R

            // (?<name>\S+)                : function name
            // (?<expression>\S+)*         : first expression (if any)
            // (?<whitespace>\s+)(?<separator>(,))\s+(?<expression>\S+))* 
            //                             : other expressions (if any)
            // (?<result>\S+)              : result
            String pattern = @"(?<name>\S+) (?<whitespace>\s+) 
                               \( 
                               ((?<expression>\S+) 
                               ((?<whitespace>\s*)(?<separator>(,))(?<whitespace>\s*)(?<expression>\S+))*)*
                               \) 
                               (?<whitespace>\s+)
                               (?<result>\S+)
                               ";

            if (Regex.IsMatch(input, pattern, RegexOptions.IgnorePatternWhitespace))
            {
                Match match = Regex.Match(input, pattern, RegexOptions.IgnorePatternWhitespace);

                // function name, arguments and result
                _Name = match.Groups["name"].Value;
                foreach (Capture capture in match.Groups["expression"].Captures)
                {
                    _Arguments.Add(new Argument(capture.Value));
                }
                _Result = new Result(match.Groups["result"].Value);
            }
            else
            {
                throw new Exception("Function ERROR!!!");
            }
        }
    }
}
